//
//  RegisterTableVC.m
//  Cunli
//
//  Created by lilubin on 15/7/24.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "RegisterTableVC.h"
#import "NSString+MD5.h"
#import "MyDataService.h"
#import "JKCountDownButton.h"
#import "SettingTableViewCell.h"
#import "SettingTableViewCell2.h"
#import "UserAgreementVC.h"
#import "SetPasswordTableVC.h"


#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height

static NSString *kSettingCellID = @"SettingTableViewCell";


@interface RegisterTableVC () <UITableViewDataSource, UITableViewDelegate>
{
//    UIButton *_checkBtn; //勾选同意按钮
}

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation RegisterTableVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavAttributes];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setNavAttributes
{
    UIImageView *navBgImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64)];
    [navBgImgView setImage:[UIImage imageNamed:@"NavigationBgImage"]];
    [self.view addSubview:navBgImgView];
    
    UILabel *navLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, 44)];
    [navLabel setText:@"注册"];
    [navLabel setTextColor:[UIColor whiteColor]];
    [navLabel setFont:[UIFont boldSystemFontOfSize:19]];
    navLabel.textAlignment = NSTextAlignmentCenter;
    [navBgImgView addSubview:navLabel];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(8, 27, 30, 30);
    [backBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
    backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    nextBtn.frame = CGRectMake(kScreenWidth-72, 27, 65, 30);
    nextBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [nextBtn addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
    [nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:nextBtn];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight-64) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.bounces = NO;
    [self.view addSubview:_tableView];
    [_tableView setBackgroundColor:[UIColor colorWithHexString:UIBgColorValue]];
    [self.view setBackgroundColor:[UIColor colorWithHexString:UIBgColorValue]];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SettingTableViewCell *cell = [[NSBundle mainBundle] loadNibNamed:kSettingCellID owner:self options:nil].lastObject;
    if (indexPath.row == 0) {
        cell.titleLabel.text = @"+86";
        cell.textField.placeholder = @"输入手机号";
        cell.textField.font = [UIFont systemFontOfSize:17];
    }
    else
    {
        SettingTableViewCell2 *cell2 = [[NSBundle mainBundle] loadNibNamed:@"SettingTableViewCell2" owner:self options:nil].lastObject;
        cell2.getNumBtnClicked = ^(void){
            [self getCheckNum];
        };
        return cell2;
        
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 61;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 61)];
    footerView.userInteractionEnabled = YES;
    
    /*
    _checkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _checkBtn.frame = CGRectMake(30, 26, 30, 30);
    [_checkBtn setImage:[UIImage imageNamed:@"checkboxno.png"] forState:UIControlStateNormal];
    [_checkBtn setImage:[UIImage imageNamed:@"checkboxyes.png"] forState:UIControlStateSelected];
    [_checkBtn addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
    _checkBtn.selected = YES;
    [footerView addSubview:_checkBtn];
    */
    
    UILabel *promptLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 5, kScreenWidth, 21)];
    promptLabel.text = @"验证码发送可能会有延迟，请耐心等待或重新获取";
    promptLabel.font = [UIFont systemFontOfSize:12];
    promptLabel.textColor = [UIColor colorWithHexString:InfoCellIntroduceColorValue];
    [footerView addSubview:promptLabel];
    
    UILabel *agreeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 21, kScreenWidth, 40)];
    [agreeLabel setText:@"点击下一步即表示同意用户使用条款"];
    [agreeLabel setFont:[UIFont systemFontOfSize:14]];
    [agreeLabel setTextAlignment:NSTextAlignmentCenter];
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:agreeLabel.text];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"0x2fa9f4"] range:NSMakeRange(10, 6)];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:InfoCellIntroduceColorValue] range:NSMakeRange(0, 10)];
    agreeLabel.userInteractionEnabled = YES;
    agreeLabel.attributedText = str;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushToAgreement)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    agreeLabel.userInteractionEnabled = YES;
    [agreeLabel addGestureRecognizer:tap];
    
    [footerView addSubview:agreeLabel];
    return footerView;
}

/*
- (void)btnAction
{
    _checkBtn.selected = !_checkBtn.selected;
}
*/

- (void)pushToAgreement
{
    UserAgreementVC *agreeVC = [[UserAgreementVC alloc] init];
    agreeVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical ;
    agreeVC.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:agreeVC animated:YES completion:NULL];
}

- (void)backAction
{
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)nextAction
{
//    if (_checkBtn.selected == YES)
//    {
        SettingTableViewCell *cell1 = (SettingTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        NSString *username = cell1.textField.text;
        
        SettingTableViewCell2 *cell2 = (SettingTableViewCell2 *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
        NSString *checkNum = cell2.checkTextField.text;
        
        if (username.length != 11 || checkNum.length != 4) {
            [Config showHUDWithText:@"请检查电话号与验证码" andImage:@"error"];
            return;
        }
        NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:4];
        
        [params setObject:username forKey:@"username"];
        [params setObject:@"rp" forKey:@"ctype"];
        [params setObject:checkNum forKey:@"code"];
        [params setObject:[NSString getSignFromParam:params] forKey:@"sign"];
        
        [MyDataService requestURL:@"checkcaptcha.php" httpMethod:@"POST" params:params fileDatas:nil complection:^(id result) {
            
            NSLog(@"RegisterVC: Checkcode result:%@", result);
            [Config saveUserName:params[@"username"]];
            NSString *response = [result objectForKey:@"response"];
            
            if ([response isEqualToString:@"captcha"])
            {
                NSDictionary *captchaDic = [result objectForKey:@"captcha"];
                NSString *code_token = [captchaDic objectForKey:@"code_token"];
                [self pushToSetPasswordVCWithCodeToken:code_token];
            }
            else
            {
                NSDictionary *errorDic = [result objectForKey:@"error"];
                NSString *errorStr = [errorDic objectForKey:@"text"];
                [Config showHUDWithText:errorStr andImage:@"error"];
                return;
            }
        } failureAction:^{
            [Config showHUDWithText:@"验证码错误" andImage:@"error"];
            return;
        }];
//    }
    /*
    else
    {
        [Config showHUDWithText:@"请选择同意用户使用条款" andImage:@"error"];
    }
     */
    
}

- (void)getCheckNum
{
    SettingTableViewCell *cell1 = (SettingTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    NSString *username = cell1.textField.text;
    
    SettingTableViewCell2 *cell2 = (SettingTableViewCell2 *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    JKCountDownButton *jkBtn = cell2.cellBtn;
    
    if (username.length == 11) {
        jkBtn.enabled = NO;
        //button type要 设置成custom 否则会闪动
        [jkBtn startWithSecond:90];
        
        [jkBtn didChange:^NSString *(JKCountDownButton *countDownButton,int second) {
            NSString *title = [NSString stringWithFormat:@"%d秒",second];
            return title;
        }];
        [jkBtn didFinished:^NSString *(JKCountDownButton *countDownButton, int second) {
            countDownButton.enabled = YES;
            return @"获取验证码";
        }];
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:2]; //获取验证码需要的参数
    
    //设置获取验证码需要的参数：username, rp, sign
    [params setObject:username forKey:@"username"];
    [params setObject:@"rp" forKey:@"ctype"];
    [params setObject:[NSString getSignFromParam:params] forKey:@"sign"];
    
    //发送获取验证码的请求
    [MyDataService requestURL:@"captcha.php" httpMethod:@"POST" params:params fileDatas:nil complection:^(id result) {
        NSLog(@"result:%@", result);
        NSString *code = result[@"code"];
        NSString *response = result[@"response"];
        NSLog(@"response:%@, code:%@", response, code);
        if ([response isEqualToString:@"error"]) {
            NSDictionary *errorDic = result[@"error"];
            NSString *errorStr = errorDic[@"text"];
            [Config showHUDWithText:errorStr andImage:@"error"];
//            if ([errorStr isEqualToString:@"该帐号已存在"]) {
                [jkBtn stop];
//            }
        }
        
    } failureAction:^{
        [self showHUDWithText:@"验证码获取错误" andImage:@"error"];
    }];
}



- (void)pushToSetPasswordVCWithCodeToken:(NSString *)codeToken
{
    SetPasswordTableVC *setPasswordVC = [[SetPasswordTableVC alloc] init];
    setPasswordVC.code_token = codeToken;
    setPasswordVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical ;
    setPasswordVC.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:setPasswordVC animated:YES completion:NULL];
}

- (void)showHUDWithText:(NSString *)str andImage:(NSString *)imgStr
{
    MBProgressHUD *hud = [Config createHUD];
    hud.mode = MBProgressHUDModeCustomView;
    hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imgStr]];
    hud.labelText = str;
    [hud hide:YES afterDelay:1];
}

@end
